/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: 1.c
> Author:cjy
> Mail: 
> Created Time: 2024年08月08日 星期四 15时32分25秒
***************************************************/

#include "queue.h"
#include "threadpool.h"
int flag = 1;
void fun(int sig){
	flag = 0;	
	printf("guanbichenggong\n");
}
void *fun1(void *arg)// 生产者
{
    THP *p = (THP *)arg;
    int data1 = 0,data2 = 0;
    DAT data;
    while(flag == 1)
    {
        data1++;
        data2++;
	data.num1 = data1;
        data.num2 = data2;
        sem_wait(&p->semw);
        pthread_mutex_lock(&p->mutex);
        // printf("请输入data1:\n");
        // scanf("%d",&p->que->data.num1);
        // printf("请输入data2:\n");
        // scanf("%d",&p->que->data.num2);
        push(data,p->que);
        
        pthread_mutex_unlock(&p->mutex);
	sem_post(&p->semr);
	printf("入队:%d %d\n",p->que->data.num1,p->que->data.num2);
    }
	printf("shengchamzhe   end\n");
}

void *fun2(void *arg)// 消费者
{
    THP *p = (THP *)arg;
    DAT dat;
    int sum = 0;
    while(flag == 1)
    {
        
        sem_wait(&p->semr);
        pthread_mutex_lock(&p->mutex);
        printf("%ld",pthread_self()%100);
        dat = front(p->que);
        sem_post(&p->semw);
        pthread_mutex_unlock(&p->mutex);
	sum = dat.num1 + dat.num2;
        printf("sum = %d\n",sum);
        pop(p->que);
	sleep(1);
    }
	
	printf("xxxxxxxxxx  %ld end\n",pthread_self()%100);
}
int main()
{
    int threads = 5;
    int queue_length = 5;
    // 创建消费者
    THP * p = create_threadpool(threads,queue_length,fun2);
    // 创建队列
    p->que = create_queue();
    sem_init(&p->semw,0,queue_length);
    // 初始化读信号
    sem_init(&p->semr,0,0);
    // 创建生产者
    pthread_t tid1 = 0;
    int ret = 0;
    ret = pthread_create(&tid1,NULL,fun1,p);
    if(ret != 0)
    {
        perror("pthread_create");
        exit(-1);
    }

	signal(SIGINT,fun);
	while(1){
		printf("%d",flag);
		if(flag == 0){
		
				break;		
			}
		sleep(1);
	}
	destroy_threadpool(p);
	if (isempty(p->que) != 0){
		delLinkMem(p->que);
	}
	printf("lianbiaokong\n");

	sem_post(&p->semr);
    pthread_join(tid1,NULL);

    

    sem_destroy(&p->semw);


    return 0;

}



